// 取消订单
import { PACKAGE_ORDER_PAGE } from '../../../constants/route';
import { ORDER_REFUND_REASON, ORDER_AFTER_SALE_TYPE, PRODUCT_RECEIVING_STATUS } from '../../../constants/order';
import { MESSAGE_ID } from '../../../constants/message';
import { redirectTo, subscribeMessage } from '../../../common/env';
import { getAfterSaleOrderInfo } from '../../../biztools/wex';
import { createAfterSaleOrder } from '../../api/order';

Page({
    data: {
        orderInfo: {},
        remark: '',
        showRemarkModal: false,
        reason: '',
        reasonList: ORDER_REFUND_REASON,
        showReasonModal: false,
    },
    onLoad: function (options) {
        // 获取本地保存的订单详情
        const orderInfo = getAfterSaleOrderInfo();
        console.log('OrderCancel => 当前订单详情：', orderInfo);
        this.setData({
            orderInfo,
        });
    },
    openRemarkModal: function () {
        this.setData({
            showRemarkModal: true,
        });
    },
    changeRemark: function (event) {
        console.log('OrderCancel => 修改的备注为：', event.detail);
        this.setData({
            remark: event.detail,
        });
    },
    openReasonModal: function () {
        this.setData({
            showReasonModal: true,
        });
    },
    changeReason: function (event) {
        console.log('OrderCancel => 选择退款原因：', event.detail.value);
        this.setData({
            reason: event.detail.value,
        });
    },
    // 取消订单
    cancelOrderAction: async function () {
        const { remark, reason, orderInfo } = this.data;
        const params = {
            orderSerialNumber: orderInfo.serialNumber,
            type: ORDER_AFTER_SALE_TYPE.all,
            afterSaleReason: reason,
            remark,
            details: orderInfo.details.map(item => {
                return {
                    orderDetailId: item.orderDetailId,
                    quantity: item.quantity,
                    goodsReceivingStatus: PRODUCT_RECEIVING_STATUS.no,
                };
            }),
        };
        // 提交取消订单
        const res = await createAfterSaleOrder(params);
        console.log('OrderCancel => 整单取消结果', res);
        if (res) {
            await subscribeMessage([MESSAGE_ID.order_aftersale]);
            // 跳转到售后单详情
            redirectTo(PACKAGE_ORDER_PAGE.orderAfterSaleDetail, {
                orderNumber: res.serialNumber,
            });
        }
    },
})